package com.ittao.taoaicodemother.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.ittao.taoaicodemother.annotation.AuthCheck;
import com.ittao.taoaicodemother.common.BaseResponse;
import com.ittao.taoaicodemother.common.DeleteRequest;
import com.ittao.taoaicodemother.common.ResultUtils;
import com.ittao.taoaicodemother.constant.UserConstant;
import com.ittao.taoaicodemother.exception.BusinessException;
import com.ittao.taoaicodemother.exception.ErrorCode;
import com.ittao.taoaicodemother.exception.ThrowUtils;
import com.ittao.taoaicodemother.mapper.UserMapper;
import com.ittao.taoaicodemother.model.dto.user.*;
import com.ittao.taoaicodemother.model.entity.User;
import com.ittao.taoaicodemother.model.enums.UserRoleEnum;
import com.ittao.taoaicodemother.model.vo.user.LoginUserVO;
import com.ittao.taoaicodemother.model.vo.user.UserVO;
import com.ittao.taoaicodemother.service.UserService;
import com.mybatisflex.core.paginate.Page;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserMapper userMapper;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public BaseResponse<Long> useRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest,
                                               HttpServletRequest request) {
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 获取当前登录用户
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(loginUser));
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 创建用户
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        // 1. 基础参数校验
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userAddRequest.getUserAccount();

        // 2. 完善账号格式校验（参考register逻辑）
        if (StrUtil.hasBlank(userAccount)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短（至少4位）");
        }

        // 3. 检查账号是否存在（包括逻辑删除的账号，绕过逻辑删除机制）
        User existingUser = userMapper.selectIgnoreLogicDelete(userAccount);

        if (existingUser != null) {
            // 3.1 若账号已被逻辑删除，则恢复该账号
            if (existingUser.getIsDelete() == 1) {
                // 复制请求参数到已有用户对象
                BeanUtil.copyProperties(userAddRequest, existingUser);

                // 设置默认密码（保持原逻辑）
                final String DEFAULT_PASSWORD = "12345678";
                existingUser.setUserPassword(userService.getEncryptPassword(DEFAULT_PASSWORD));

                // 恢复账号（取消逻辑删除）
                existingUser.setIsDelete(0);

                // 绕过逻辑删除机制更新
                int updateResult = userMapper.updateIgnoreLogicDelete(existingUser);
                ThrowUtils.throwIf(updateResult == 0, ErrorCode.SYSTEM_ERROR, "恢复用户失败，数据库错误");

                return ResultUtils.success(existingUser.getId());
            } else {
                // 3.2 若账号未删除，则提示已存在
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号已存在");
            }
        }

        // 4. 账号不存在，正常创建新用户
        User user = new User();
        BeanUtil.copyProperties(userAddRequest, user);

        // 设置默认密码（保持原逻辑）
        final String DEFAULT_PASSWORD = "12345678";
        user.setUserPassword(userService.getEncryptPassword(DEFAULT_PASSWORD));

        // 确保必要默认值
        if (user.getUserRole() == null) {
            user.setUserRole(UserRoleEnum.USER.getValue());
        }

        boolean saveResult = userService.save(user);
        ThrowUtils.throwIf(!saveResult, ErrorCode.OPERATION_ERROR, "创建用户失败，数据库错误");

        return ResultUtils.success(user.getId());
    }

    /**
     * 根据 id 获取用户（仅管理员）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id) {
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 删除用户 (仅管理员)
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 仅管理员和用户本身可以更新用户信息
        User loginUser = userService.getLoginUser(request);
        Long userId = userUpdateRequest.getId();
        if (loginUser == null || (!loginUser.getId().equals(userId) && !loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE))) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 修改用户密码
     */
    @PostMapping("/update/password")
    public BaseResponse<Boolean> updateUserPassword(@RequestBody UserUpdatePasswordRequest userUpdatePasswordRequest,
                                                    HttpServletRequest request) {
        if (userUpdatePasswordRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }

        String oldPassword = userUpdatePasswordRequest.getOldPassword();
        String newPassword = userUpdatePasswordRequest.getNewPassword();

        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);

        // 调用服务层方法修改密码
        boolean result = userService.updateUserPassword(oldPassword, newPassword, loginUser);

        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "密码修改失败");
        return ResultUtils.success(true);
    }

    /**
     * 分页查询（仅管理员）
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        int current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotalPage());
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }

    /**
     * 文件上传图片（可重新上传）
     */
    @PostMapping(value = "/upload/file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public BaseResponse<String> uploadPictureByFile(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String pictureUrl = userService.uploadPicture(multipartFile, loginUser);
        return ResultUtils.success(pictureUrl);
    }

    /**
     * 通过 url 上传图片（可重新上传）
     */
    @PostMapping("/upload/url")
    public BaseResponse<String> uploadPictureByUrl(String fileUrl, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String pictureUrl = userService.uploadPicture(fileUrl, loginUser);
        return ResultUtils.success(pictureUrl);
    }
}
